<template>
  <div>
    <div class="timeline-time-wrap">
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="finishedText"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="getList()"
      >
        <Empty v-if="!list.length" description="暂无跟进历史记录" />
        <ul class="infinite-list" style="overflow: auto">
          <li v-for="(unit, i) in list" :key="i" class="infinite-list-item">
            <div class="timeline-time" v-if="unit[0].createTime">
              {{ dateFormat(unit[0].createTime, 'yyyy-MM-dd w') }}
            </div>
            <van-steps active="nu" direction="vertical" class="timeline-box" inactive-icon="-" active-icon="-">
              <van-step
                class="timeline-box-item"
                v-for="(item, index) in unit"
                :key="index"
                placement="top"
                type="primary"
              >
                <span class="timeline-box-item-timestamp" v-if="item.createTime">
                  {{ item.createTime.slice(10, 16) }}
                </span>
                <p class="timeline-box-item-title" v-if="item.recordStatusFullName">
                  {{ item.recordStatusFullName || '-' }}
                </p>
                <div class="flex timeline-box-item-content" v-for="(item1, index1) in item.contents" :key="index1">
                  <span class="timeline-box-item-content-name">{{ item1.itemKey || '-' }}:</span>
                  <div class="item-content gap10 gap5" v-for="(item2, index2) in item1.itemValue" :key="index2">
                    <div v-html="item2.content"></div>

                    <template v-if="item2.isAttachment == 1">
                      <a
                        v-for="(item3, index3) in item2.attachments"
                        :key="index3"
                        target="_blank"
                        class="link"
                        @click.prevent="previewFile(item3)"
                      >
                        {{ item3.title || '-' }}
                      </a>
                    </template>
                    <!-- <a class="timeline-box-item-content-value link" @click.prevent="downloadFile(c)" v-if="c.flag">
                    {{ c.value || '-' }}
                  </a>
                  <pre class="timeline-box-item-content-value flex1" v-else>{{ c.value || '-' }}</pre> -->
                  </div>
                </div>
              </van-step>
            </van-steps>
          </li>
        </ul>
      </van-list>
    </div>
    <!-- 图片/视频预览 -->
    <Preview v-model="previewFileObj.visible" :urlList="previewFileObj.url" :type="previewFileObj.type" />
  </div>
</template>

<script>
import { getFollowRecordList, read } from '../api'
import { dateFormat } from '@/utils'
// import { downloadFromUrl } from '@/utils/common'
import Preview from './Preview'
export default {
  name: '',
  components: { Preview },
  props: {
    // 是否为数据展示
    isData: {
      type: Boolean,
      default: false,
    },
    data: {},

    // 线索跟进人表Id
    id: {
      type: String,
      default: null,
    },
    // 当前线索Id
    leadId: {
      type: String,
      default: null,
    },
    // 当前跟进人id
    followUserId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      loading: false,
      query: {
        pageNum: 1,
        pageSize: 10,
        weLeadsId: '',
        followUserId: '',
      },
      refreshing: false,
      finished: false,
      finishedText: '看到底啦~',
      error: false,
      list: [],
      dateFormat,
      previewFileObj: {},
    }
  },
  watch: {},
  created() {},
  methods: {
    initData(data) {
      if (!data) {
        return []
      }
      const list = []
      const dayList = []

      // 提取天
      data.forEach((ele) => {
        ele.createTime = ele.createTime
        // || this.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
        const date = this.dateFormat(ele.createTime, 'yyyyMMdd')
        dayList.includes(date) || dayList.push(date)
      })
      dayList.sort((a, b) => b - a)
      // 提取每天的时间点
      for (let i = 0; i < dayList.length; i++) {
        const timeList = []
        for (let j = 0; j < data.length; j++) {
          if (dayList[i] === this.dateFormat(data[j].createTime, 'yyyyMMdd')) {
            timeList.push(data[j])
          }
        }
        list.push(timeList)
      }

      return list
    },
    getList(page) {
      if (this.isData) {
        this.list.push([this.data])
        this.finished = true
        return
      }
      this.loading = true
      this.finished = false

      // if (this.categoryId) {
      //   this.query.categoryId = this.categoryId
      // }
      this.query.id = this.id
      this.query.weLeadsId = this.leadId
      this.query.followUserId = this.followUserId
      page && (this.query.pageNum = page)
      getFollowRecordList(this.query)
        .then(({ rows, total }) => {
          if (this.query.pageNum == 1) {
            this.list = []
          }

          this.list.push(...this.initData(rows))
          this.loading = false
          this.refreshing = false
          // 数据全部加载完成
          this.finished = true
          if (this.list.length >= +total) {
            this.finished = true
          } else {
            this.query.pageNum++
          }
        })
        .catch(() => {
          this.error = true
          this.loading = false
        })
    },
    previewFile(row) {
      // 附件类型 0 图片（image）、1 语音（voice）、2 视频（video），3 普通文件(file)
      if ([0, 2].includes(row.type)) {
        row.visible = true
        this.previewFileObj = row
      } else {
        window.open(row.url)
      }
    },
    // 下载
    // downloadFile(row) {
    //   const { value, url } = row,
    //     name = value
    //   let type = this.getTypeFromName(name)
    //   switch (type) {
    //     case 0:
    //     case 2:
    //       this.$emit('preview', url, type)
    //       break

    //     default:
    //       downloadFromUrl(url, name)
    //       break
    //   }
    // },
    // getTypeFromName(name) {
    //   let r = 0
    //   // type： 0 图片（image）、1 语音（voice）、2 视频（video），3 普通文件(file)
    //   let obj = name.split('.'),
    //     name_len = obj.length,
    //     suffix = name_len > 1 ? obj[name_len - 1].toLowerCase() : 'unknow'
    //   // if (['png', 'jpg', 'jpeg'].includes(suffix)) type = 0
    //   if (['amr'].includes(suffix)) r = 1
    //   else if (['mp4', 'mov'].includes(suffix)) r = 2
    //   else if (['xls', 'xlsx', 'doc', 'docx', 'pdf', 'ppt', 'pptx', 'pps', 'pptsx'].includes(suffix)) r = 3
    //   return r
    // },
  },
}
</script>

<style lang="less" scoped>
.timeline-time-wrap {
  background: #ffffff;
  box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.02), 0px 40px 20px 0px rgba(0, 0, 0, 0.02);
  border-radius: 12px;
  padding: 0 20px 10px;
}
.infinite-list-item {
  border-bottom: 1px solid #eee;
  &:last-child {
    border: 0;
  }
}
.timeline-time {
  font-size: 14px;
  color: #999999;
  line-height: 48px;
}
.timeline-box {
  padding-left: 70px;
  &-item {
    &-timestamp {
      position: absolute;
      top: 9px;
      left: -65px;
      margin: 0;
      color: #86909c;
      font-size: 12px;
    }

    &-title {
      font-weight: 700;
      line-height: 1.2;
      margin-bottom: 5px;
      color: @color;
    }
    &-content {
      margin-bottom: 5px;
      overflow: hidden;
      &-name {
        color: #86909c;
        margin-right: 5px;
        white-space: nowrap;
      }
      .item-content {
        color: #333;
        white-space: normal;
        word-break: break-all;
        & .link {
          background: rgba(63, 126, 242, 0.1);
          border-radius: 4px;
          border: 1px solid #3f7ef2;
          padding: 3px 10px;
          transition: all 0.3s;
          display: inline-block;
        }
      }
    }
    & ::v-deep .van-step__icon {
      width: 12px;
      height: 12px;
      background: @color;
      border-radius: 50%;
    }
    &:first-child ::v-deep .van-step__icon {
      border-radius: 0;
    }
  }
}
::v-deep .at-user {
  color: @color;
  padding: 0 3px;
}
</style>
